package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CusterException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 黑马程序员
 * @since 2022-06-06
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    //    @Autowired
//    private DishFlavorService dishFlavorService;
    @GetMapping("/page")
    public R<Page> pageSelect(int page, int pageSize, String name) {


        log.info("page = {},pageSize = {}", page, pageSize);
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        //添加过滤条件
        qw.like(name != null, Dish::getName, name);
        //添加排序条件
        qw.orderByAsc(Dish::getUpdateTime);
        //调用方法
        dishService.page(pageInfo);
        //数据拷贝
//        BeanUtils.copyProperties(pageInfo,dish);

        List<Dish> records = pageInfo.getRecords();
        Set<Long> collect = records.stream().map(dish -> (dish.getCategoryId())).collect(Collectors.toSet());

        List<Category> categories = categoryService.listByIds(collect);

        Map<Long, String> collect1 = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));

        for (Dish record : records) {
            Long categoryId = record.getCategoryId();
            String dishName = collect1.get(categoryId);
            record.setCategoryName(dishName);

        }
        pageInfo.setRecords(records);
//        BeanUtils.copyProperties(dish,pageInfo);

        return R.success(pageInfo);
    }

    @PostMapping
    public R<String> saveDto(@RequestBody DishDto dto) {
        log.info(dto.toString());

        LambdaQueryWrapper<DishDto> qw = new LambdaQueryWrapper();
        qw.orderByAsc(DishDto::getUpdateTime);
        dishService.saveByDto(dto);

        return R.success("添加成功");
    }

    @GetMapping("{id}")
    public R<DishDto> getByDishId(@PathVariable Long id) {
//            log.info("id值为{}",id);
        DishDto byDishId = dishService.getByDishId(id);
        return R.success(byDishId);
    }

    @PutMapping
    public R<String> save(@RequestBody DishDto dto) {
        dishService.updateByDto(dto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("更新成功");
    }

    @PostMapping("/status/0")
    public R<String> updateByStatus0(@RequestParam List<Long> ids) {
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(0);
        }
        dishService.saveOrUpdateBatch(dishes);
        return R.success("状态修改成功");
    }

    @PostMapping("/status/1")
    public R<String> updateByStatus1(@RequestParam List<Long> ids) {
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            dish.setStatus(1);
        }
        dishService.saveOrUpdateBatch(dishes);
        return R.success("状态修改成功");
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        dishService.deleteByids(ids);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("删除成功");
    }

    /**
     * 修改之前先进行数据回显
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> selectByCategory(Dish dish) {
        List<DishDto> dishDtoList;
        String key ="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper();
        qw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        qw.eq(Dish::getStatus, 1);
        //添加排序条件
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> dishList = dishService.list(qw);

        //把dishid收集到一个set集合中
        Set<Long> dishIdSet = dishList.stream()
                .map(item -> item.getId())
                .collect(Collectors.toSet());
        //通过菜品id获取对应的口味信息,封装到list集合中
        LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
        qw1.in(DishFlavor::getDishId, dishIdSet);
        List<DishFlavor> dishFlavorlist = dishFlavorService.list(qw1);

        // //3)循环遍历给flavors成员变量赋值
         dishDtoList = new ArrayList<>();
        for (Dish dish1 : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            //从所有的口味信息中筛选出当前菜品的口味信息
            Long dishId = dishDto.getId();
            //添加过滤条件找到符合id的口味信息
            List<DishFlavor> dishFlavorCollect = dishFlavorlist.stream()
                    .filter(dishFlavor -> dishId.equals(dishFlavor.getDishId()))
                    .collect(Collectors.toList());
            dishDto.setFlavors(dishFlavorCollect);
            dishDtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(key,dishDtoList);
        return R.success(dishDtoList);
    }

}

